<template>
  <Header />
  <div class="bookshelf">
    <h1>我的书架</h1>
    <div class="book-list">
      <div class="book-item" v-for="book in bookshelf" :key="book.id">
        <img :src="`${imgBaseUrl}${book.picUrl}`" alt="书籍封面" class="book-cover" />
        <div class="book-info">
          <h2>{{ book.bookName }}</h2>
          <p>作者：{{ book.authorName }}</p>
          <button @click="removeFromBookshelf(book.bookId)">移出书架</button>
        </div>
      </div>
    </div>
    <div class="add-book">
      <h2>添加书籍到书架</h2>
      <input v-model="newBookId" placeholder="输入书籍ID" />
      <button @click="addToBookshelf">加入书架</button>
    </div>
  </div>
  <Footer />
</template>

<script>
import { reactive, onMounted, toRefs } from 'vue';
import { getBookshelfByUserId, addBookToShelf, removeBookFromShelf } from '@/api/user'; // 调整为新的API名称
import Header from '@/components/common/Header';
import Footer from '@/components/common/Footer';
import { getUserId } from '@/utils/auth'; // 引入获取用户ID的工具函数

export default {
  name: 'MyBookshelf',
  components: {
    Header,
    Footer,
  },
  setup() {
    const state = reactive({
      bookshelf: [],
      imgBaseUrl: process.env.VUE_APP_BASE_IMG_URL,
      newBookId: '',
      userId: getUserId(), // 获取用户ID
    });

    onMounted(async () => {
      await loadBookshelf();
    });

    const loadBookshelf = async () => {
      try {
        const { data } = await getBookshelfByUserId(state.userId); // 动态替换 userId
        state.bookshelf = data;
      } catch (error) {
        console.error('加载书架失败:', error);
      }
    };

    const addToBookshelf = async () => {
      if (!state.newBookId) return;
      try {
        await addBookToShelf({ userId: state.userId, bookId: state.newBookId });
        state.newBookId = '';
        await loadBookshelf();
      } catch (error) {
        console.error('添加书籍失败:', error);
      }
    };

    const removeFromBookshelf = async (bookId) => {
      try {
        await removeBookFromShelf(state.userId, bookId);
        await loadBookshelf();
      } catch (error) {
        console.error('移除书籍失败:', error);
      }
    };

    return {
      ...toRefs(state),
      addToBookshelf,
      removeFromBookshelf,
    };
  },
};
</script>

<style>
.book-list {
  display: flex;
  flex-wrap: wrap;
}
.book-item {
  margin: 10px;
}
.book-cover {
  width: 100px;
  height: auto;
}
.add-book {
  margin-top: 20px;
}
</style>
